/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  // const targetArr = []
  // for(let i = 0, length = nums.length; i < length - 1; i++) {
  //     const temp = nums[i];
  //     for(let j = i+1; j < length; j++) {
  //         if (temp + nums[j] === target) {
  //             targetArr.push([i, j]);
  //             break;
  //         }
  //     }
  // }
  // return targetArr;
  var a = {};
  for (let i = 0, len = nums.length; i < len; i++) {
    var tmp = target - nums[i]
    if (a[tmp] !== undefined) return [a[tmp], i]
    a[nums[i]] = i
  }
};

// 返回所有的情况
const twoSum = (arr, target) => {
  let obj = {};
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (obj[arr[i]] != null) {
      let temp = obj[arr[i]];
      for (let j = 0; j < temp.length; j++) {
        res.push([temp[j], i]);
      }
    }
    let temp = target - arr[i];
    // obj[temp] = obj[temp] ? [...obj[temp], i] : [i];
    // 用 push 更好一点
    obj[temp] ? obj[temp].push(i) : obj[temp] = [i];
  }
  return res;
}


/**
 * 三数之和
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  nums.sort((a, b) => a - b)

  let ans = []
  let len = nums.length

  // enumerate the array, and assume the item to be the smallest one
  for (let i = 0; i < len; i++) {

    // have already enumerate the item as the smallest one among the three
    // then continue
    if (i && nums[i] === nums[i - 1]) continue

    // the sum of another two should be
    let target = -nums[i]

    // the indexes of another two 
    let [start, end] = [i + 1, len - 1]

    while (start < end) {
      let sum = nums[start] + nums[end]

      if (sum > target) {
        end--
      } else if (sum < target) {
        start++
      } else {
        ans.push([nums[i], nums[start], nums[end]])

        // remove the duplication
        while (nums[start] === nums[start + 1])
          start++
        start++

        // remove the duplication
        while (nums[end] === nums[end - 1])
          end--
        end--
      }
    }
  }

  return ans
}

// 输入：nums = [-1,0,1,2,-1,-4]
// 输出：[[-1, -1, 2], [-1, 0, 1]]

/**
 * n 数之和
 */
function getAllCombin(array, n, sum, temp = []) {
  if (temp.length === n) {
    if (temp.reduce((t, c) => t + c) === sum) {
      return temp;
    }
    return;
  }
  for (let i = 0; i < array.length; i++) {
    const current = array.shift();
    temp.push(current);
    const result = getAllCombin(array, n, sum, temp);
    if (result) {
      return result;
    }
    temp.pop();
    array.push(current);
  }
}
const arr = [1, 2, 3, 4, 5, 6];

console.log(getAllCombin(arr, 3, 10));